package com.dora.kafka.messaging;

import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.stereotype.Component;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.util.concurrent.ListenableFutureCallback;

/**
 * Kafka生产者
 *
 * @author Clarence
 * @date 2024/03/03
 */
@Component
@Slf4j
public class KafkaProducer {

    @Autowired
    private KafkaTemplate<String, Object> kafkaTemplate;

    //自定义topic
    public static final String TOPIC_TEST = "topic.test";

    //消费者组1
    public static final String TOPIC_GROUP1 = "topic.group1";

    //消费者组2
    public static final String TOPIC_GROUP2 = "topic.group2";

    /**
     * 发送值消息
     *
     * @param value 值
     */
    public void sendMessageWithValue(Object value) {
        String value2String = JSON.toJSONString(value);
        log.info("准备发送消息体为：{}", value2String);
        kafkaTemplate.send(TOPIC_TEST, value2String);
    }

    /**
     * 发送键值消息
     *
     * @param key   键
     * @param value 值
     */
    public void sendMessageWithKeyValue(String key, Object value) {
        String value2String = JSON.toJSONString(value);
        log.info("准备发送消息，键为：{}，体为：{}", key, value2String);
        kafkaTemplate.send(TOPIC_TEST, key, value);
    }

    /**
     * 发送同步回调消息
     *
     * @param object 对象
     */
    public void sendCallbackMessage(Object object) {
        String obj2String = JSON.toJSONString(object);
        log.info("准备发送消息为：{}", obj2String);
        //发送消息
        ListenableFuture<SendResult<String, Object>> future = kafkaTemplate.send(TOPIC_TEST, object);
        future.addCallback(new ListenableFutureCallback<SendResult<String, Object>>() {
            @Override
            public void onFailure(Throwable throwable) {
                //发送失败的处理
                log.info(TOPIC_TEST + " - 生产者 发送消息失败：{}", throwable.getMessage());
            }

            @Override
            public void onSuccess(SendResult<String, Object> stringObjectSendResult) {
                //成功的处理
                log.info(TOPIC_TEST + " - 生产者 发送消息成功：{}", stringObjectSendResult.toString());
            }
        });
    }
}
